using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
using TCEntity;

namespace TCDbService
{
  public class AccountService
  {
    readonly TCDbContext _context;
    public AccountService(TCDbContext context)
    {
      _context = context;
    }

    static void JudgeNull(User user)
    {
      if (user == null)
        throw new ArgumentNullException(nameof(user));
      var username = user.Username;
      var password = user.Password;
      if (username == null || password == null || username == "" || password == "")
        throw new ArgumentException("用户名或密码为空。");
    }
    public async Task RegisterAsync(User user)
    {
      JudgeNull(user);
      if (await _context.Users.AnyAsync(member => user.Username == member.Username))
        throw new ArgumentException("用户名已存在。");
      _context.Add(user);
      await _context.SaveChangesAsync();
    }
    public async Task<User> LoginAsync(User user)
    {
      JudgeNull(user);
      var member = await _context.Users.FindAsync(user.Username);
      if (member == null)
        throw new ArgumentException("用户不存在。");
      if (member.Password != user.Password)
        throw new InvalidOperationException("用户名或密码错误");
      return member;
    }
    public async Task ChangePswdAsync(User user, string password)
    {
      if (password == null) throw new ArgumentNullException(nameof(password));
      var member = await LoginAsync(user);
      if (member.Password == password) throw new ArgumentException("新密码与旧密码重复。");
      member.Password = password;
      await _context.SaveChangesAsync();
    }
    public async Task DeleteAsync(User user)
    {
      var member = await LoginAsync(user);
      _context.Remove(member);
      await _context.SaveChangesAsync();
    }

  }
}
